package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate>  dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            //日期计算，指定日期的最后一条对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> doubleList = new  ArrayList<>();
            //计算每天的营业额
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", localDateTimeBegin);
            map.put("end", localDateTimeEnd);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //当天没有的话是为null，需要判断，若为null返回0
            turnover = turnover==null ? 0.0 :turnover;
            doubleList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))//StringUtils.join(）将一个集合（如列表、数组等）中的元素连接成一个字符串，并使用指定的分隔符分隔各个元素。
                .turnoverList(StringUtils.join(doubleList, ","))
                .build();

        return turnoverReportVO;
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate>  dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> allUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", localDateTimeBegin);
            map.put("end", localDateTimeEnd);
            //到当前日期的总用户数量
            Integer allUser=userMapper.getAllUserByTime(localDateTimeEnd);
            allUser = allUser==null ? 0 :allUser;
            allUserList.add(allUser);
            //当前日期的新用户数
            Integer newUser=userMapper.countByMap(map);
            newUser = newUser==null ? 0 :newUser;
            newUserList.add(newUser);
        }

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(allUserList, ","))
                .build();

        return userReportVO;
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getorderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate>  dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
           begin = begin.plusDays(1);
           dateList.add(begin);
        }
        List<Integer> totalList = new ArrayList<>();
        List<Integer> validList = new ArrayList<>();
        int totals = 0;
        int valids = 0;
        for (LocalDate localDate : dateList) {
            LocalDateTime localDateTimeBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime localDateTimeEnd = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", localDateTimeBegin);
            map.put("end", localDateTimeEnd);
            map.put("status", Orders.COMPLETED);
            //查询到当前日期的总订单量
            Integer total = orderMapper.getAllOrdersByTime(map);
            //防止当前日期总订单量为空
            total = total==null ? 0 :total;
            //添加到当前日期期间内的总订单量
            totals = totals +total;
            totalList.add(total);

            //查询到当前日期的有效订单量
            Integer valid=orderMapper.countByMap(map);
            valid = valid==null ? 0 :valid;
            valids = valids+valid;
            validList.add(valid);
        }
        //或者通过steam流方式计算totals valids
        // reduce 是 Stream API 的归约操作，用于将流中的所有元素合并成一个结果。
        // Integer::sum 是一个方法引用，等价于 (a, b) -> a + b，表示对两个整数进行相加。reduce 会依次对流的元素进行累加
        // reduce 返回的是 Optional<Integer>，因为如果 totalList 是空的，reduce 不会返回有效值。
        // get() 是 Optional 的方法，直接取出值，但如果 Optional 为空（即 totalList 为空），会抛出 NoSuchElementException。
        Integer  totalss= totalList.stream().reduce(Integer::sum).get();//reduce：合并  sum：求和 get()：获取返回值
        Integer validss = validList.stream().reduce(Integer::sum).get();

        Double completionRate = 0.0;
        if(totals != 0){
            completionRate = (double) valids /totals;
        }
        

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalList, ","))
                .validOrderCountList(StringUtils.join(validList, ","))
                .orderCompletionRate( completionRate)
                .totalOrderCount(totals)
                .validOrderCount(valids)
                .build();
        return orderReportVO;
    }

    /**
     * 统计指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalestop10(LocalDate begin, LocalDate end) {

        LocalDateTime localDateTimeBegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(localDateTimeBegin, localDateTimeEnd);
        //通过steam流方式获取到菜品名称 数量 的集合
        // map:使用 map 方法对每个 GoodsSalesDTO 对象应用 getName() 方法，提取 name 字段。
        // collect: 把 Stream 里的元素**收集（Collect）**到一个可变的结果容器
        // 使用 Collectors.toList() 将流中的 String 元素收集到一个新的 List<String> 中
        Collection<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .numberList(StringUtils.join(numberList, ","))
                .nameList(StringUtils.join(nameList, ","))
                .build();


        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //1.查询数据库，获取营业数据 -查询近三十天的营业数据  minusDays（30）日期前30天 LocalDate：年月日   LocalDateTime：年月日时分秒
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime localDateTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime localDateTimeEnd = LocalDateTime.of(dateEnd, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(localDateTime, localDateTimeEnd);
        //2.通过POI将数据写入到Excel文件中
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            //填充数据 - 时间
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin + "至" + dateEnd);
            //获取第四行并填值
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获取第五行
            XSSFRow row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //填充明细数据
            for(int i= 0 ;i<30 ;i++){
                LocalDate localDate = dateBegin.plusDays(i);
                LocalDateTime localDateTimeMIN = LocalDateTime.of(localDate, LocalTime.MIN);
                LocalDateTime localDateTimeMAX = LocalDateTime.of(localDate, LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.getBusinessData(localDateTimeMIN, localDateTimeMAX);

                //获取某一行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(localDate.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }




    }
}
